package cz.hanis.android.geography.xml;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import cz.hanis.android.geography.models.Test;


public class TestHandler extends DefaultHandler {

	private static final String TESTS = "tests";
	private static final String TEST = "test";
	private static final String ID = "id";
	private static final String CLASS = "class";
	private static final String TIME = "time";
	

	private final Stack<String> tagsStack = new Stack<String>();
	String value = null;

	private List<Test> testList;
	private Test test;

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		String parentTag = peekTag();		
		pushTag(qName);
		
		if (localName.equals(TESTS)) {
			testList = new ArrayList<Test>();
		} else if (localName.equals(TEST)) {           
            test = new Test();
		}		
	}
    
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
        String tag = peekTag();
        if (!qName.equals(tag)) {
            throw new InternalError();
        }
        popTag();
        String parentTag = peekTag();		

		if (localName.equals(TEST)) {           
			testList.add(test);					
		} else if (localName.equals(ID)) {		
            test.setId(value);
        } else if (localName.equals(CLASS)) {		
            test.setClassName(value);
        } else if (localName.equals(TIME)) {		
            test.setTime(Integer.valueOf(value));
        }	

	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		value = new String(ch, start, length);
	}

	public List<Test> getTestList() {
		return testList;
	}

	private void pushTag(String tag) {
		tagsStack.push(tag);
	}

	private String popTag() {
		return tagsStack.pop();
	}

	private String peekTag() {
		if(tagsStack.isEmpty()) {
			return null;
		}
		return tagsStack.peek();
	}

}
